Parent-Child relationships in Generic Fluent Models

Let’s use the example of Continent ↤⇉ Country from Generic Pre-populated Models in Fluent

That is a one - to many relationship, where for one Continent there are multiple Countries. And not vice-versa.


Add Generic Parent to Country

//Country ⇇↦  Continent
extension Country {
  var owner: Parent<Country, Continent<Database>>? {
    return parent(\.continentID)
  }
}

That Requires That Referential Integrity is Defined for Country

  static func prepareFields(on connection: Database.Connection) -> Future<Void> {
    return Database.create(Country<Database>.self, on: connection) { builder in
      //add fields
      ...
      //indexes
      ...
      
      //referential integrity - foreign key to parent
      try builder.addReference(from: \Country<D>.continentID, to: \Continent<D>.id, actions: .init(update: .update, delete: .nullify))
    }
  }

Add Generic Children To Continent

//Continent ↤⇉ Country
extension Continent {
  var countries: Children<Continent, Country<Database>> {
    return children(\.continentID)
  }
}


Prev: Making a New Vapor Package Part 2

Next: Adding Pagination To Vapor Query


Vapor 3 Tutorial Start




#tutorial #fluent #vapor #model #migration #db #generic #one-to-many #many-to-one #fluent #pub